﻿using System.Collections.Generic;
using CodeParser.Tokens;

namespace CodeParser.Expressions
{
    public class ArgumentListParser
        : ExpressionParser
    {

        public ArgumentListParser()
        {
            ArgumentParsers = new List<ExpressionParser>();
        }

        public override Expression Parse(Token[] tokens, int index)
        {
            if (tokens[index].Type == TokenType.RoundOpen)
            {
                var argumentList = new ArgumentList {OpenBracket = tokens[index]};
                argumentList.StringIndex = argumentList.OpenBracket.Index;
                argumentList.Add(new SingleToken() { Token = argumentList.OpenBracket});
                var closeIndex = ParseUtils.FindClosingBracket(tokens, index, TokenType.RoundOpen, TokenType.RoundClose);
                var length = closeIndex.HasValue ? closeIndex.Value - index + 1 : tokens.Length - index;
                if (closeIndex.HasValue)
                {
                    argumentList.CloseBracket = tokens[closeIndex.Value];
                }
                argumentList.TokenLength = length;
                var arguments = ParseUtils.SplitTokenChain(tokens, index + 1, length - (closeIndex.HasValue ? 2 : 1), TokenType.Comma);
                if (!(arguments.Count == 1 && arguments[0].Count == 0))
                {
                    foreach (var argument in arguments)
                    {
                        if (argument.Count > 0)
                        if (argument[0].Type != TokenType.Comma)
                        {
                            var argumentExpression = ParseSubExpression(argument.ToArray(), 0, null, ArgumentParsers);
                            argumentList.Arguments.Add(argumentExpression);
                            argumentList.Add(argumentExpression);
                        }
                        else
                        {
                            argumentList.Add(new SingleToken() { Token = argument[0]});
                        }
                    }
                }
                if (argumentList.CloseBracket != null) argumentList.Add(new SingleToken() { Token = argumentList.CloseBracket});

                var lastToken = tokens[index + argumentList.TokenLength - 1];
                argumentList.StringLength = lastToken.Index + lastToken.Value.Length - argumentList.StringIndex;

                return argumentList;
            }
            return null;
        }

        public List<ExpressionParser> ArgumentParsers { get; set; }

    }
}
